package com.sxdx.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxdx.common.Result;
import com.sxdx.entity.LoginUser;
import com.sxdx.entity.Menu;
import com.sxdx.mapper.MenuMapper;
import com.sxdx.service.IMenuService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 展示不同用户的不同菜单，实现权限控制
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public  List getMenuTree(LoginUser loginUser) {
        String userId = loginUser.getUserId();
        //先从redis中查询缓存,查到的是权限(菜单)树List<Auth>转的json串
        String authTreeListJson = stringRedisTemplate.opsForValue().get(userId + ":authTree");
        if(StringUtils.hasText(authTreeListJson)){//redis中查到缓存
            //将json串转回权限(菜单)树List<Auth>并返回
            List<Menu> authTreeList = JSON.parseArray(authTreeListJson, Menu.class);
            return authTreeList;
        }
        //redis中没有查到缓存,从数据库表中查询所有权限(菜单)
        List<Menu> allMenuList = menuMapper.findAllMenu(userId);
        //将所有权限(菜单)List<Auth>转成权限(菜单)树List<Auth>
        List<Menu> menuTreeList = allMenuToMenuTree(allMenuList, 0);
        //将权限(菜单)树List<Auth>转成json串并保存到redis
        stringRedisTemplate.opsForValue().set(userId + ":authTree", JSON.toJSONString(menuTreeList));
        //返回权限(菜单)树List<Auth>
        return menuTreeList;
    }



    //将所有权限(菜单)转成权限(菜单)树的递归算法
    private List<Menu> allMenuToMenuTree(List<Menu> allMenuList, int parentId){
        //获取父权限(菜单)id为参数parentId的所有权限(菜单)
        //【parentId最初为0,即最初查的是所有一级权限(菜单)】
        List<Menu> menuList = new ArrayList<>();
        for (Menu menu : allMenuList) {
            if(String.valueOf(menu.getParentId()).equals(String.valueOf(parentId))){
                menuList.add(menu);
            }
        }
        //查询List<Auth> authList中每个权限(菜单)的所有子级权限(菜单)
        for (Menu menu : menuList) {
            List<Menu> childAuthList = allMenuToMenuTree(allMenuList, Integer.parseInt(menu.getMenuId()));
            menu.setChildMenu(childAuthList);
        }
        return menuList;
    }
}
